package com.example;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 打开 http://localhost:8081/Demo/HelloWorld
 * @author:gaoruishan
 * @time:2022/11/28 13:20
 * @email:grs0515@163.com
 */
// 扩展 HttpServlet 类
public class HelloWorld extends HttpServlet {

    private String message;

    public void init() throws ServletException {
        super.init();
        // 执行必需的初始化
        message = "Hello World";
        System.out.println("----init---");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 调用会提示：HTTP Status 405 - HTTP method GET is not supported by this URL
        // super.doGet(request, response);
        System.out.println("----doGet---");
        // 设置响应内容类型
        response.setContentType("text/html");
        // 实际的逻辑是在这里
        PrintWriter writer = response.getWriter();
        writer.write("<h1>" + message + "</h1>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        super.doPost(request, response);
        System.out.println("----doPost---");
    }

    public void destroy() {
        // 什么也不做
        System.out.println("----destroy---");
    }
}